struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x)
        : val(x), next(nullptr)
    {
    }
};

class Solution
{
public:
    ListNode *reverseBetween(ListNode *head, int m, int n)
    {
        ListNode *dummyHead = new ListNode(0);
        dummyHead->next = head;
        ListNode *cur = head;
        ListNode *pre = dummyHead;
        while (--m)
        {
            pre = pre->next;
            cur = cur->next;
        }
        for (int i = 0; i < n - m; ++i)
        {
            ListNode *next = cur->next;
            cur->next = next->next;
            next->next = pre->next;
            pre->next = next;
        }
        return dummyHead->next;
    }
};